<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>新增采购订单</title>
<script type="text/javascript">
    Ext.onReady(function () {
        //以销定采
        var purchaseBaseOnSales = '<%=@purchaseBaseOnSales%>';

        //是否临时保存
        var temporary = Ext.create('Ext.form.field.Hidden', {
            name: 'temporary',
            value: 0
        });

        var company = Ext.create('Ext.form.ComboBox', {
            store: companyAllInfoStore,
            fieldLabel: '所属公司',
            allowBlank: false,
            blankText: "所属公司必须选择",
            valueField: 'id',
            displayField: 'name',
            name: 'company_id',//如果不想提交displayField，则在这儿指定要提交的Key，value就是valueField．
            emptyText: '请选择...',
            loadingText: '搜索中...',
            anchor: '95%',
            //pageSize: 10,
            readOnly: false,
            minChars: 0,
            editable: false
        });

        //备注
        var desc = Ext.create('Ext.form.field.Text', {
            fieldLabel: '备注',
            name: 'description',
            anchor: '97%'
        });

        //供应商
        var vendor = Ext.create('Ext.form.ComboBox', {
            store: vendorStore,
            fieldLabel: '供应商',
            allowBlank: false,
            blankText: "供应商必须选择",
            valueField: 'id',
            displayField: 'name',
            name: 'vendor_id',//如果不想提交displayField，则在这儿指定要提交的Key，value就是valueField．
            emptyText: '请选择...',
            loadingText: '搜索中...',
            anchor: '95%',
            //pageSize: 10,
            readOnly: false,
            minChars: 0,
            editable: false
        });

        vendor.on('select', function (combo, record, index) {
            linkman.setValue(record[0].get('linkman'));
            phone.setValue(record[0].get('phone'));
        });

        //要求发货时间
        var actionDate = Ext.create('Ext.form.field.Date', {
            fieldLabel: '到货日期',
            allowBlank: false,
            name: 'action_date',
            format: 'Y-m-d', //格式化日期
            //disabledDays: [0,6],	//不让选择周六，周日
            //disabledDaysText: "周末要休息",
            invalidText: "您输入的日期格式不对，正确格式为2010-01-18",
            blankText: "到货日期必须选择",
            anchor: '95%',
            emptyText: '到货日期...'
        });
        //合同号
        var contractNumber = Ext.create('Ext.form.field.Text', {
            fieldLabel: '合同编号',
            allowBlank: true,
            name: 'contract_number',
            anchor: '95%'
        });

        //联系人
        var linkman = Ext.create('Ext.form.field.Text', {
            fieldLabel: '联系人',
            name: 'linkman',
            anchor: '95%',
            allowBlank: false
        });

        //联系电话
        var phone = Ext.create('Ext.form.field.Text', {
            fieldLabel: '联系电话',
            name: 'phone',
            anchor: '95%',
            allowBlank: false
        });

        //税率
        var taxRate = Ext.create('Ext.form.field.Number', {
            fieldLabel: '税率(%)',
            name: "tax_rate",
            allowBlank: false,
            allowDecimals: true,
            minValue: 0,
            maxValue: 100,
            value: 17,
            anchor: '95%'
        });

        var deliveryAddress = Ext.create('Ext.form.field.Text', {
            fieldLabel: '送货地址',
            allowBlank: false,
            name: 'delivery_address',
            value: '<%=@purchasingShippingAddress%>',
            anchor: '95%'
        });

        //总金额
        var sumAmount = Ext.create('Ext.form.field.Number', {
            fieldLabel: '总金额',
            name: "amount",
            readOnly: true,
            allowBlank: false,
            allowDecimals: true,
            minValue: 0,
            anchor: '90%'
        });

        //总进项税
        var sumVATAmount = Ext.create('Ext.form.field.Number', {
            fieldLabel: '总税额',
            name: "value_added_tax_amount",
            readOnly: true,
            allowBlank: false,
            allowDecimals: true,
            minValue: 0,
            anchor: '90%'
        });

        //含税总金额
        var sumTaxAmount = Ext.create('Ext.form.field.Number', {
            fieldLabel: '含税总金额',
            name: "tax_amount",
            readOnly: true,
            allowBlank: false,
            allowDecimals: true,
            minValue: 0,
            anchor: '90%'
        });
        //--------------------------------------------------------------------------

        //销售订单CBB
        var saleOrderNumberCBB = Ext.create('Ext.form.ComboBox', {
            store: saleOrderNumberStore,
            allowBlank: false,
            blankText: "销售订单必须选择",
            emptyText: '请选择...',
            displayField: 'order_number',
            hideTrigger: false,
            loadingText: '搜索中...',
            anchor: '100%',
            pageSize: 10,
            minChars: 0
        });

        saleOrderNumberCBB.on('select', function (combo, record, index) {
            var purchaseOrderItemRecord = purchaseOrderDetailSM.getSelected();
            if (!purchaseOrderItemRecord) {
                return false;
            }
            purchaseOrderItemRecord.reject();
            purchaseOrderItemRecord.set('sale_order_id', records[0].get('id'));
            purchaseOrderItemRecord.set('sale_order_number', records[0].get('order_number'));
        });

        //产品列表
        var productCBB = Ext.create('Ext.form.ComboBox', {
            store: productAllInfoStore,
            emptyText: '请选择...',
            displayField: 'name',
            loadingText: '搜索中...',
            anchor: '100%',
            pageSize: 10,
            minChars: 0,
            listConfig: {
                loadingText: 'Searching...',
                getInnerTpl: function () {
                    return '<div style="float:left; width:200px" data-qtip="{name}">{name:ellipsis(18)}</div><div style="float:left; width:110px">{number}</div>{is_suit}';
                }
            }
        });

        productCBB.on('select', function (combo, record, index) {
            var records = purchaseOrderDetailGrid.getSelectionModel().getSelection();
            var purchaseOrderItemRecord = records[0];
            if (!purchaseOrderItemRecord) {
                return false;
            }
            //打开了，重复的记录不允许存在(暂时去掉)，也就是说重复的记录也可以存在。
            if (isDuplicateBySaleOrderProduct(purchaseOrderDetailDS, purchaseOrderItemRecord.get('sale_order_id'), record[0].get('product_id'))) {
                //删除当前记录
                purchaseOrderDetailDS.remove(purchaseOrderItemRecord);
            } else {
                purchaseOrderItemRecord.set('number', record[0].get('number'));
                purchaseOrderItemRecord.set('spec', record[0].get('spec'));
                purchaseOrderItemRecord.set('unit', record[0].get('unit'));
                purchaseOrderItemRecord.set('unit_price', record[0].get('unit_price'));
                purchaseOrderItemRecord.set('amount', record[0].get('unit_price'));
                purchaseOrderItemRecord.set('quantity', record[0].get('quantity'));
                purchaseOrderItemRecord.set('product_id', record[0].get('id'));
                //判断套装
                purchaseOrderItemRecord.set('is_suit', record[0].get('is_suit'));

                /*Ext.Ajax.request({
                 url : '/stock/getProductStockQuantity',
                 success : function (result, request) {
                 purchaseOrderItemRecord.set('stock_quantity_1',result.responseText.split("|")[0]);
                 purchaseOrderItemRecord.set('stock_quantity_2',result.responseText.split("|")[1]);
                 if (purchaseOrderItemRecord.get('sale_order_id') != 0){
                 //限制即时最大采购数
                 Ext.Ajax.request({
                 url : '/purchase_order/getProductQuantityForPurchase',
                 success : function (result, request) {
                 purchaseOrderItemRecord.set('quantity',result.responseText);
                 purchaseOrderItemRecord.set('balance_quantity',result.responseText);
                 getSumAmount();
                 },
                 failure : function (result, request){
                 Ext.MessageBox.show({
                 title: '消息',
                 msg: "通讯失败，请从新操作1",
                 buttons: Ext.MessageBox.OK,
                 icon: Ext.MessageBox.WARNING
                 });
                 },
                 method : 'GET',
                 params : {
                 sale_order_id : purchaseOrderItemRecord.get('sale_order_id'),
                 product_id : record.get('product_id')
                 }
                 });
                 } else{
                 purchaseOrderItemRecord.set('balance_quantity',1000000);
                 }
                 },
                 failure : function (result, request){
                 Ext.MessageBox.show({
                 title: '消息',
                 msg: "通讯失败，请从新操作2",
                 buttons: Ext.MessageBox.OK,
                 icon: Ext.MessageBox.WARNING
                 });
                 },
                 method : 'GET',
                 params : {
                 id : record.get('product_id')
                 }
                 });
                 */
            }
        });

        /*productCBB.on('focus', function(combo, record, index) {
         var records = purchaseOrderDetailGrid.getSelectionModel().getSelection();
         productStore.extraParams.id = records[0].get('sale_order_id');
         productStore.extraParams.start=0;
         productStore.extraParams.limit=10;
         productStore.load();
         });*/

        //采购订单列表Grid Store
        Ext.define('PurchaseOrderDetailAddModel', {
            extend: 'Ext.data.Model',
            fields: [
                {name: 'id'},
                {
                    name: 'sale_order_id'
                },
                {
                    name: 'number'
                },
                {
                    name: 'name'
                },
                {
                    name: 'description'
                },
                {
                    name: 'unit_price',
                    type: 'float'
                },
                {
                    name: 'tax_price',
                    type: 'float'
                },
                {
                    name: 'tax_amount',
                    type: 'float'
                },
                {
                    name: 'value_added_tax',
                    type: 'float'
                },
                {
                    name: 'quantity',
                    type: 'int'
                },
                {
                    name: 'product_id'
                },
                {name: 'product_name'},
                {
                    name: 'amount',
                    type: 'float'
                },
                {
                    name: 'is_suit',
                    convert: function (value, record) {
                        if (value == "1") {
                            return "套装";
                        } else if (value == "0") {
                            return "单品";
                        } else {
                            return value;
                        }
                    }
                }
            ]
        });

        var purchaseOrderDetailDS = Ext.create('Ext.data.Store', {
            //autoDestroy : true,
            model: 'PurchaseOrderDetailAddModel',
            proxy: {
                type: 'ajax',
                reader: {
                    type: 'json',
                    root: 'root',
                    totalProperty: 'totalProperty'// 数据集记录总数
                }
            }
        });

        //生成要订单的产品的Grid
        var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
            clicksToEdit: 1
        });

        var purchaseOrderDetailGrid = Ext.create('Ext.grid.Panel', {
            store: purchaseOrderDetailDS,
            plugins: [cellEditing],
            columns: [Ext.create('Ext.grid.RowNumberer'), {
                header: '销售订单Id',
                dataIndex: 'sale_order_id',
                hidden: true,
                width: 30
            }, {
                header: '销售订单',
                dataIndex: 'sale_order_number',
                field: saleOrderNumberCBB,
                hidden: true,
                width: 195
            }, {
                header: '产品名称',
                dataIndex: 'product_name',
                field: productCBB,
                width: 370
            }, {
                header: '产品ID',
                dataIndex: 'product_id',
                width: 50,
                hidden: true
            }, {
                header: '产品编号',
                dataIndex: 'number',
                width: 95
            }, {
                header: '规格',
                dataIndex: 'spec',
                width: 50
            }, {
                header: '单位',
                dataIndex: 'unit',
                width: 50
            }, {
                header: '数量',
                dataIndex: 'quantity',
                field: Ext.create('Ext.form.field.Number', {
                    allowBlank: false,
                    allowDecimals: false,
                    minValue: 1
                }),
                align: 'right',
                width: 50
            }, {
                header: '工库',
                dataIndex: 'stock_quantity_1',
                align: 'right',
                renderer: stockQuantityRender,
                hidden: true,
                width: 50
            }, {
                header: '大库',
                dataIndex: 'stock_quantity_2',
                align: 'right',
                renderer: stockQuantityRender,
                hidden: true,
                width: 50
            }, {
                header: '单价',
                dataIndex: 'unit_price',
                renderer: Ext.util.Format.numberRenderer('0,000.0000000000'),
                align: 'right',
                width: 110
            }, {
                header: '金额',
                dataIndex: 'amount',
                renderer: Ext.util.Format.numberRenderer('0,000.00'),
                align: 'right',
                width: 70
            }, {
                header: '含税单价',
                dataIndex: 'tax_price',
                field: Ext.create('Ext.form.field.Number', {
                    allowBlank: false,
                    allowDecimals: true,
                    minValue: 0,
                    decimalPrecision: 2
                }),
                renderer: Ext.util.Format.numberRenderer('0,000.00'),
                align: 'right',
                width: 80
            }, {
                header: '进项税',
                dataIndex: 'value_added_tax',
                renderer: Ext.util.Format.numberRenderer('0,000.00'),
                align: 'right',
                width: 70
            }, {
                header: '含税金额',
                dataIndex: 'tax_amount',
                renderer: Ext.util.Format.numberRenderer('0,000.00'),
                align: 'right',
                width: 80
            }, {
                header: '套装',
                dataIndex: 'is_suit',
                width: 50
            }, {
                header: '备注',
                dataIndex: 'description',
                width: 90,
                field: Ext.create('Ext.form.field.Text', {
                    name: 'description',
                    anchor: '90%'
                })
            }, {
                header: '销售采购差',
                dataIndex: 'balance_quantity',
                width: 90,
                hidden: true
            }],
            selModel: Ext.create('Ext.selection.CheckboxModel'),
            width: 1170,
            height: 315,
            //title: '进货品种列表',

            tbar: [
                {
                    text: '添加产品',
                    iconCls: 'addItem',
                    handler: function () {
                        var record = null;
                        if (purchaseBaseOnSales === '否') {
                            record = Ext.ModelManager.create({
                                product_name: '请选择产品',
                                sale_order_id: 0,
                                sale_order_number: '无销售订单关联'
                            }, purchaseOrderDetailGrid.getStore().model);
                            //saleOrderNumberCBB.setDisabled(true);
                        } else {
                            record = Ext.ModelManager.create({
                                sale_order_number: '无销售订单关联'
                            }, purchaseOrderDetailGrid.getStore().model);
                        }
                        purchaseOrderDetailDS.insert(0, record);
                    }
                },
                {
                    text: '删除',
                    iconCls: 'remove',
                    handler: function () {
                        var records = purchaseOrderDetailGrid.getSelectionModel().getSelection();
                        cellEditing.cancelEdit();
                        purchaseOrderDetailDS.remove(records);
                        getSumAmount();
                    }
                }
            ]
        });

        purchaseOrderDetailGrid.on('itemdblclick', function (gridPanel, record, item, index, e, options) {
            var productId = purchaseOrderDetailDS.getAt(index).get('product_id');
            var tt = new Ext.ToolTip({
                target: e.target,
                width: 200,
                autoLoad: {url: 'stock/simpleStockForToolTipByProductId?product_id=' + productId + "t=" + (new Date()).getTime()},
                dismissDelay: 20000 // auto hide after 15 seconds
            });
        });


        //提交按钮
        var submitButton = Ext.create('Ext.Button', {
            text: '提交',
            tooltip: '提交采购订单。',
            iconCls: 'icon-save',
            handler: function () {
                if (purchaseOrderFormPanel.form.isValid()) {

                    var productsJsonStr = gridStoreToJson(purchaseOrderDetailDS, rejectKeyArray);
                    if (purchaseOrderDetailDS.getCount() == 0 || productsJsonStr === "") {
                        Ext.MessageBox.show({
                            title: '提示',
                            msg: "您还没有选择有效的产品或选择的产品数量为0！",
                            buttons: Ext.MessageBox.OK,
                            icon: Ext.MessageBox.INFO
                        });
                        return;
                    }

                    //检查一下，有没有销售，产品，价格三元素完全相同的记录存在。如果存在就要检查
                    if (isDuplicateForPurchase(purchaseOrderDetailDS)) {
                        Ext.MessageBox.show({
                            title: '消息',
                            msg: "有销售，产品，价格三者完全相同的记录存在，请检查！",
                            buttons: Ext.MessageBox.OK,
                            icon: Ext.MessageBox.INFO
                        });
                        return;
                    }
                    this.disable();
                    var allJsonStr = purchaseOrderFormPanel.getForm().getValues();
                    allJsonStr = Ext.JSON.encode(allJsonStr);
                    allJsonStr = Ext.util.Format.substr(allJsonStr, 0, allJsonStr.length - 1);
                    allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";
                    //alert(allJsonStr);
                    Ext.Ajax.request({
                        url: '/purchase_order/create',
                        success: function (result, request) {
                            if (Ext.JSON.decode(result.responseText).info.indexOf("成功") > -1) {
                                Ext.MessageBox.show({
                                    title: '消息',
                                    msg: "新增采购订单，操作成功！",
                                    buttons: Ext.MessageBox.OK,
                                    icon: Ext.MessageBox.INFO
                                });
                            }
                            else {
                                Ext.MessageBox.show({
                                    title: '消息',
                                    msg: Ext.JSON.decode(result.responseText).info,
                                    buttons: Ext.MessageBox.OK,
                                    icon: Ext.MessageBox.WARNING
                                });
                            }
                            newPurchaseOrderWin.destroy();
                        },
                        failure: function (result, request) {
                            Ext.MessageBox.show({
                                title: '消息',
                                msg: "通讯失败，请从新操作3",
                                buttons: Ext.MessageBox.OK,
                                icon: Ext.MessageBox.WARNING
                            });
                            newPurchaseOrderWin.destroy();
                        },
                        method: 'POST',
                        params: {
                            data: Ext.JSON.encode(allJsonStr),
                            authenticity_token: authToken.getValue()
                        }
                    });
                }
            }
        });

        //临时保存按钮
        var tempSaveButton = Ext.create('Ext.Button', {
            text: '暂存',
            tooltip: '暂时保存采购订单。',
            iconCls: 'temp-save',
            handler: function () {
                if (vendor.getRawValue() === vendor.getValue()) {
                    vendor.reset();
                }

                //首先把临时变量设置为1
                temporary.setValue(1);

                if (purchaseOrderFormPanel.form.isValid()) {
                    var productsJsonStr = gridStoreToJson(purchaseOrderDetailDS, rejectKeyArray);
                    if (purchaseOrderDetailDS.getCount() == 0 || productsJsonStr === "") {
                        Ext.MessageBox.show({
                            title: '提示',
                            msg: "您还没有选择有效的产品或选择的产品数量为0！",
                            buttons: Ext.MessageBox.OK,
                            icon: Ext.MessageBox.INFO
                        });
                        return;
                    }

                    //没有添加产品，则提示
                    if (purchaseOrderDetailDS.getCount() == 0 || productsJsonStr === "") {
                        Ext.MessageBox.show({
                            title: '提示',
                            msg: "您还没有选择有效的产品或选择的产品数量为0！",
                            buttons: Ext.MessageBox.OK,
                            icon: Ext.MessageBox.INFO
                        });
                        return;
                    }

                    //检查一下，有没有销售，产品，价格三元素完全相同的记录存在。如果存在就要检查
                    if (isDuplicateForPurchase(purchaseOrderDetailDS)) {
                        Ext.MessageBox.show({
                            title: '消息',
                            msg: "有销售，产品，价格三者完全相同的记录存在，请检查！",
                            buttons: Ext.MessageBox.OK,
                            icon: Ext.MessageBox.INFO
                        });
                        return;
                    }

                    this.disable();
                    var allJsonStr = purchaseOrderFormPanel.getForm().getValues();
                    allJsonStr = Ext.JSON.encode(allJsonStr);
                    allJsonStr = Ext.util.Format.substr(allJsonStr, 0, allJsonStr.length - 1);
                    allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";

                    Ext.Ajax.request({
                        url: '/purchase_order/create',
                        success: function (result, request) {
                            if (Ext.JSON.decode(result.responseText).info.indexOf("成功") > -1) {
                                Ext.MessageBox.show({
                                    title: '消息',
                                    msg: "暂存采购订单，操作成功！",
                                    buttons: Ext.MessageBox.OK,
                                    icon: Ext.MessageBox.INFO
                                });
                            }
                            else {
                                Ext.MessageBox.show({
                                    title: '消息',
                                    msg: Ext.JSON.decode(result.responseText).info,
                                    buttons: Ext.MessageBox.OK,
                                    icon: Ext.MessageBox.WARNING
                                });
                            }
                            newPurchaseOrderWin.destroy();
                        },
                        failure: function (result, request) {
                            Ext.MessageBox.show({
                                title: '消息',
                                msg: "通讯失败，请从新操作4",
                                buttons: Ext.MessageBox.OK,
                                icon: Ext.MessageBox.WARNING
                            });
                            newPurchaseOrderWin.destroy();
                        },
                        method: 'POST',
                        params: {
                            data: Ext.JSON.encode(allJsonStr),
                            authenticity_token: authToken.getValue()
                        }
                    });
                }
            }
        });

        //暂时保存按钮
        var closeButton = Ext.create('Ext.Button', {
            text: '关闭',
            tooltip: '关闭当前窗口，并且当前编辑的信息不能保存。',
            iconCls: 'exit',
            handler: function () {
                newPurchaseOrderWin.destroy();
            }
        });

        //采购申请的FormPanel
        var purchaseOrderFormPanel = Ext.create('Ext.form.Panel', {
            fieldDefaults: {
                labelWidth: 65,
                labelAlign: 'right'
            },
            width: 1183,
            frame: true,
            url: '/purchase_order/create',
            method: 'GET',
            items: [
                {
                    layout: 'column',
                    xtype: 'container',
                    items: [
                        {
                            columnWidth: .2,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [company]
                        },{
                            columnWidth: .25,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [vendor]
                        },
                        {
                            columnWidth: .17,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [actionDate]
                        },
                        {
                            columnWidth: .17,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [contractNumber]
                        },
                        {
                            columnWidth: .16,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [taxRate]
                        }
                    ]
                },
                {
                    layout: 'column',
                    xtype: 'container',
                    items: [
                        {
                            columnWidth: .2,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [linkman]
                        },
                        {
                            columnWidth: .25,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [phone]
                        },
                        {
                            columnWidth: .55,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [deliveryAddress]
                        }
                    ]
                },
                {
                    layout: 'column',
                    xtype: 'container',
                    items: [
                        {
                            columnWidth: 1,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [desc]
                        }
                    ]
                },
                {
                    layout: 'column',
                    xtype: 'container',
                    items: [
                        {
                            columnWidth: 1,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [purchaseOrderDetailGrid]
                        }
                    ]
                },
                {
                    layout: 'column',
                    xtype: 'container',
                    items: [
                        {
                            columnWidth: 0.25,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [sumAmount]
                        },
                        {
                            columnWidth: 0.25,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [sumVATAmount]
                        },
                        {
                            columnWidth: 0.25,
                            layout: 'anchor',
                            xtype: 'container',
                            items: [sumTaxAmount]
                        }
                    ]
                },
                temporary
            ],
            buttons: [submitButton, tempSaveButton, closeButton]
        });
        purchaseOrderFormPanel.render('new_purchase_order');
        //
        purchaseOrderDetailGrid.on('edit', afterEdit, this);

        function afterEdit(editor, obj, options) {

            if (obj.field == "product_name" || obj.field == "quantity" || obj.field == "tax_price") {
                var balanceQuantity = 0;
                if (obj.record.get('balance_quantity') != '') {
                    balanceQuantity = obj.record.get('balance_quantity');
                }

                //balanceQuantity,其实是，针对某销售订单得到采购时最大可以采购的产品数量
                //不实行以销定采，暂时屏蔽掉。
                /*if (obj.record.get('quantity') > balanceQuantity ){
                 obj.record.set('quantity',obj.record.get('balance_quantity'));
                 }*/

                if (obj.record.get('quantity') > 0) {
                    //设置含税单价和含税竞价
                    obj.record.set('unit_price', Math.round(10000000000 * obj.record.get('tax_price') / (1 + taxRate.getValue() * 0.01)) / 10000000000);
                    obj.record.set('tax_amount', obj.record.get('tax_price') * obj.record.get('quantity'));
                    obj.record.set('amount', Math.round(obj.record.get('quantity') * 100 * obj.record.get('unit_price')) / 100);
                    obj.record.set('value_added_tax', Math.round(obj.record.get('amount') * taxRate.getValue() * 0.01 * 1000) / 1000);
                } else {
                    obj.record.set('amount', 0);
                }
            }
            getSumAmount();
        }

        function getSumAmount() {
            sumAmount.setValue(0);
            sumVATAmount.setValue(0);
            sumTaxAmount.setValue(0);
            var records = purchaseOrderDetailDS.getRange(0, purchaseOrderDetailDS.getCount());
            for (var i = 0; i < records.length; i++) {
                var record = records[i];
                var quantity = record.get('quantity');
                var unitPrice = record.get('unit_price');
                var taxPrice = record.get('tax_price');
                //record.set('amount',quantity*unitPrice);
                //record.set('tax_amount',quantity*taxPrice);
                //var amount = record.get('amount');
                sumAmount.setValue(sumAmount.getValue() + record.get('amount'));
                sumVATAmount.setValue(sumVATAmount.getValue() + record.get('value_added_tax'));
                sumTaxAmount.setValue(sumTaxAmount.getValue() + record.get('tax_amount'));
            }
        }
    })
</script>
</head>
<body>
<div id="new_purchase_order"></div>
</body>
</html>